package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.demo.enums.UserStatus;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.*;
import com.example.demo.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2024-05-04
 * Time: 9:45
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void deductBalanceById(Long id, Integer money) {
        // 1.查询用户是否存在
        User user = this.getById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常!");
        }
        // 2.用户余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足!");
        }
        // 3.扣减余额并根据余额更改状态(涉及到并发安全，加了个乐观锁)
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance,remainBalance)
                .set(remainBalance == 0,User::getStatus,UserStatus.FREEZE)
                .eq(User::getBalance,user.getBalance()) // 乐观锁
                .eq(User::getId,id)
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null,User::getUsername,name)
                .eq(status != null,User::getStatus,status)
                .ge(minBalance != null,User::getBalance,minBalance)
                .le(maxBalance != null,User::getBalance,maxBalance)
                .list();
    }

    @Override
    public List<UserVO> queryUserAndAddressesByIds(List<Long> ids) {
        // 1.根据用户 ids 查询用户集合
        List<User> users = this.listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        // 2.转换类型
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);
        // 3.根据用户 ids 查询用户地址列表
        List<Long> userIds = userVOS.stream().map(UserVO::getId).collect(Collectors.toList());
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        // 3.1 转换类型
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> addressMap = new HashMap<>();
        if (!CollUtil.isEmpty(addressVOS)) {
           // 3.2 根据 id 分组
            addressMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        // 4.填充用户地址返回
        for (UserVO userVO : userVOS) {
            userVO.setAddresses(addressMap.get(userVO.getId()));
        }
        return userVOS;
    }

    @Override
    public PageResult<UserVO> pageQueryUser(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        // 1.构造分页条件
        Page<User> page = userQuery.toMpPage("create_time", false);
        // 2.分页查询
        Page<User> p = lambdaQuery()
                .like(name != null,User::getUsername, name)
                .eq(status != null,User::getStatus, status)
                .page(page);
        // 3.解析并封装结果
        return PageResult.of(p, new Function<User, UserVO>() {
            @Override
            public UserVO apply(User user) {
                // 1. 拷贝基础属性
                UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
                // 2.处理特殊逻辑
                userVO.setUsername(user.getUsername().substring(0,user.getUsername().length()-2)+"**");
                return userVO;
            }
        });
    }
}
